package com.ddxcloud.movie.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ddxcloud.common.handler.BusinessException;
import com.ddxcloud.movie.config.common.JwtProperties;
import com.ddxcloud.movie.config.movie.MovieConfig;
import com.ddxcloud.movie.data.constants.CouponStatusConstant;
import com.ddxcloud.movie.data.dto.BindCouponDTO;
import com.ddxcloud.movie.data.dto.CreateCodeDTO;
import com.ddxcloud.movie.data.entity.Channel;
import com.ddxcloud.movie.data.entity.UserCoupon;
import com.ddxcloud.movie.data.vo.CouponCodeVO;
import com.ddxcloud.movie.mapper.UserCouponMapper;
import com.ddxcloud.movie.service.ChannelService;
import com.ddxcloud.movie.service.CouponsService;
import com.ddxcloud.movie.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class CouponsServiceImpl implements CouponsService {

    @Resource
    ChannelService channelService;

    @Resource
    MovieConfig movieConfig;

    @Resource
    UserCouponMapper userCouponMapper;

    @Resource
    JwtProperties jwtProperties;

    @Override
    public JSONObject createCode(CreateCodeDTO dto) {
        Channel channel = channelService.getChannel();
        String url = movieConfig.getUrl() + "/open/coupons/v1/createCode";
        String result = HttpRequest.post(url)
                .header("appId", channel.getChannelId())
                .body(JSONUtil.toJsonStr(dto))
                .timeout(20000)
                .execute().body();
        return JSONObject.parseObject(result);
    }

    @Override
    public JSONObject getCodeInfo(String couponCode) {
        Channel channel = channelService.getChannel();
        String url = movieConfig.getUrl() + "/open/coupons/v1/getCodeInfo?couponCode=" + couponCode;
        String result = HttpRequest.get(url)
                .header("appId", channel.getChannelId())
                .timeout(20000)
                .execute().body();
        return JSONObject.parseObject(result);
    }

    @Override
    public List<UserCoupon> getCouponList(HttpServletRequest request) {
        String tokenName = request.getHeader(jwtProperties.getTokenName());
        if (!JwtUtil.verifyJWT(tokenName)) {
            return new ArrayList<>();
        }
        Jws<Claims> claimsJws = JwtUtil.parseJWT(tokenName);
        LambdaQueryWrapper<UserCoupon> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCoupon::getUserId, claimsJws.getPayload().get("userId").toString());
        queryWrapper.eq(UserCoupon::getChannelId, request.getHeader("channelId"));
        return userCouponMapper.selectList(queryWrapper);
    }

    @Override
    public Boolean bind(BindCouponDTO dto, HttpServletRequest request) {
        Channel channel = channelService.getChannel();
        JSONObject jsonObject = this.getCodeInfo(dto.getCouponCode());
        if (jsonObject.getInteger("code") == 0) {
            jsonObject = jsonObject.getJSONObject("data");
            CouponCodeVO couponCode = JSONUtil.toBean(jsonObject.toString(), CouponCodeVO.class);
            String tokenName = request.getHeader(jwtProperties.getTokenName());
            if (JwtUtil.verifyJWT(tokenName)) {
                Integer isExist = userCouponMapper.isExistUserCouponByCode(couponCode.getCouponCode());
                if (null != isExist) {
                    throw new BusinessException("该券码已被绑定");
                }
                Jws<Claims> claimsJws = JwtUtil.parseJWT(tokenName);
                // 绑定用户优惠券
                UserCoupon userCoupon = new UserCoupon();
                userCoupon.setChannelId(channel.getChannelId());
                userCoupon.setUserId(Long.valueOf(claimsJws.getPayload().get("userId").toString()));
                userCoupon.setCouponId(couponCode.getCouponId());
                userCoupon.setCouponTitle(couponCode.getCouponName());
                userCoupon.setCouponCode(couponCode.getCouponCode());
                userCoupon.setCouponInfo(jsonObject.toString());
                userCoupon.setCouponStatus(CouponStatusConstant.STATUS_0); // 未使用
                userCoupon.setCreateTime(couponCode.getCreateTime());
                userCouponMapper.insert(userCoupon);
                return Boolean.TRUE;
            }
        } else {
            throw new BusinessException(jsonObject.getString("msg"));
        }
        return Boolean.FALSE;
    }
}
